import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import type { Variants } from 'framer-motion';
import axios from 'axios';
import BackButton from '../components/BackButton';

interface CEQResponse {
  resp_code: string;
  balance: string;
  card_stat: string;
  trans_sn: string;
  error_msg: string;
}

const CEQ: React.FC = () => {
  const [cardNumber, setCardNumber] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<CEQResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 动画配置
  const containerVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.6,
        ease: [0.43, 0.13, 0.23, 0.96]
      }
    },
    exit: {
      opacity: 0,
      y: -20,
      transition: {
        duration: 0.5
      }
    }
  };

  const formatBalance = (balance: string): string => {
    const amount = parseInt(balance, 10) / 100;
    return amount.toFixed(2);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!cardNumber.trim()) {
      setError('请输入卡号');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const requestData = {
        pan: cardNumber.trim(),
        appid: '01'
      };

      console.log('发送请求数据:', requestData);
      
      const response = await axios.post('/api/ceq', requestData);
      console.log('收到响应:', response.data);
      
      if (response.data.resp_code !== '0') {
        setError(response.data.error_msg || '查询失败');
      } else {
        setResult(response.data);
      }
    } catch (err: any) {
      console.error('请求错误:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error_msg || '查询失败，请稍后重试';
      setError(typeof errorMessage === 'string' ? errorMessage : '查询失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const getCardStatus = (status: string): string => {
    const statusMap: { [key: string]: string } = {
      '00': '正常',
      '01': '挂失',
      '02': '冻结',
      '03': '注销'
    };
    return statusMap[status] || `未知(${status})`;
  };

  const getStatusColor = (status: string): string => {
    const colorMap: { [key: string]: string } = {
      '00': 'bg-green-100 text-green-800',
      '01': 'bg-yellow-100 text-yellow-800',
      '02': 'bg-red-100 text-red-800',
      '03': 'bg-gray-100 text-gray-800'
    };
    return colorMap[status] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#eaf2ff] via-[#f0f7ff] to-[#f8fbff] py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
      <BackButton />
      
      {/* 背景装饰 */}
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob"></div>
        <div className="absolute -bottom-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-3xl opacity-20 animate-blob animation-delay-2000"></div>
      </div>

      <motion.div
        className="max-w-3xl mx-auto"
        initial="hidden"
        animate="visible"
        variants={containerVariants}
      >
        <div className="text-center mb-10">
          <h1 className="text-4xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-500 to-purple-500">
            卡片余额查询
          </h1>
          <p className="mt-3 text-xl text-gray-600">
            快速查询卡片余额和状态信息
          </p>
        </div>

        <div className="bg-white/60 backdrop-blur-xl border border-white/30 rounded-2xl p-8 shadow-[0_8px_32px_rgba(0,0,0,0.08)]">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="cardNumber" className="block text-sm font-medium text-gray-700 mb-2">
                卡号
              </label>
              <div className="relative">
                <input
                  type="text"
                  id="cardNumber"
                  value={cardNumber}
                  onChange={(e) => setCardNumber(e.target.value)}
                  className="block w-full px-4 py-3 rounded-xl bg-white/50 border border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200 outline-none"
                  placeholder="请输入卡号"
                />
                <motion.button
                  type="submit"
                  disabled={loading}
                  className="absolute right-2 top-1/2 -translate-y-1/2 px-6 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-lg font-medium hover:shadow-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                >
                  {loading ? (
                    <div className="flex items-center">
                      <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      查询中...
                    </div>
                  ) : '查询'}
                </motion.button>
              </div>
            </div>
          </form>

          <AnimatePresence mode="wait">
            {error && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="mt-6 p-4 bg-red-50 rounded-xl border border-red-100"
              >
                <p className="text-red-800 text-sm">{error}</p>
              </motion.div>
            )}

            {result && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="mt-6 space-y-4"
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                    <p className="text-sm text-gray-500 mb-1">卡号</p>
                    <p className="text-lg font-medium text-gray-900">{cardNumber}</p>
                  </div>
                  <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                    <p className="text-sm text-gray-500 mb-1">余额</p>
                    <p className="text-lg font-medium text-gray-900">¥ {formatBalance(result.balance)}</p>
                  </div>
                </div>
                
                <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                  <p className="text-sm text-gray-500 mb-2">卡片状态</p>
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(result.card_stat)}`}>
                    {getCardStatus(result.card_stat)}
                  </span>
                </div>

                <div className="bg-white/50 backdrop-blur-sm rounded-xl p-4 border border-white/30">
                  <p className="text-sm text-gray-500 mb-1">交易流水号</p>
                  <p className="text-sm font-mono text-gray-900">{result.trans_sn}</p>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* 使用提示 */}
        <motion.div 
          className="mt-8 text-center text-gray-500 text-sm"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
        >
          <p>输入卡号后点击查询按钮即可获取卡片信息</p>
        </motion.div>
      </motion.div>
    </div>
  );
};

export default CEQ; 